import { CtlBase } from './CtlBase'
import { parseYvanPropChangeVJson } from './CtlUtils'
import { CtlMenuDefault } from './CtlDefaultValue'
import { YvEvent, YvEventDispatch } from './YvanEvent'

export class CtlMenu extends CtlBase<CtlMenu> {
  static create(module: any, vjson: any): CtlMenu {
    const that = new CtlMenu(vjson)
    that._module = module

    _.defaultsDeep(vjson, CtlMenuDefault)

    const yvanProp = parseYvanPropChangeVJson(vjson, ['data', 'onMenuItemClick'])
    // 将 vjson 存至 _webix (此时 _webix 还只是 vjson 代理对象)
    that._webixConfig = vjson


    // 将 yvanProp 合并至当前 Ctl 对象
    _.assign(that, yvanProp)

    _.merge(vjson, that._webixConfig, {
      on: {
        onInited: function (this: any) {
          that.attachHandle(this, { ...vjson, ...yvanProp })
        },
        onDestruct() {
          that.removeHandle()
        },
        onMenuItemClick(this: any, id: any) {
          const item = this.getMenuItem(id)
          YvEventDispatch(that.onMenuItemClick, that, item)
        }
      }
    })
    return that
  }

  /**
   * 树节点被点击后触发
   */
  onMenuItemClick?: YvEvent<CtlMenu, any>

  set data(data: any[]) {
    if (!this._webix) {
      _.merge(this._webixConfig, {
        data
      })
      return
    }
    this._webix.define('data', data)
    this._webix.refresh()
  }
}